<template>
  <div class="scroll-container" ref="container">
    <div class="scroll-content" ref="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HorizontalScroll',
  mounted() {
    const container = this.$refs.container

    let isDown = false
    let startX
    let scrollLeft

    // PC端实现鼠标无限滚动的监听
    container.addEventListener('mousedown', (e) => {
      isDown = true
      container.classList.add('active')
      // 获取当前鼠标按下位置
      startX = e.pageX - container.offsetLeft
      // 获取当前滚动条位置
      scrollLeft = container.scrollLeft
    })

    container.addEventListener('mouseleave', () => {
      isDown = false
      container.classList.remove('active')
    })

    container.addEventListener('mouseup', () => {
      isDown = false
      container.classList.remove('active')
    })

    container.addEventListener('mousemove', (e) => {
      if (!isDown) return
      e.preventDefault()
      // 获取当前鼠标位置-鼠标按下位置=滚动的距离
      const x = e.pageX - container.offsetLeft
      // 滚动的距离*2
      const walk = (x - startX) * 2 // scroll-fast
      // 设置滚动条位置
      container.scrollLeft = scrollLeft - walk
    })

    // 鼠标滚轮事件
    container.addEventListener('wheel', (e) => {
      e.preventDefault()
      container.scrollLeft += e.deltaY
    })

    // 移动端事件
    container.addEventListener('touchstart', (e) => {
      isDown = true
      startX = e.touches[0].pageX - container.offsetLeft
      scrollLeft = container.scrollLeft
    })

    container.addEventListener('touchend', () => {
      isDown = false
    })

    container.addEventListener('touchmove', (e) => {
      if (!isDown) return
      const x = e.touches[0].pageX - container.offsetLeft
      const walk = (x - startX) * 2 // scroll-fast
      container.scrollLeft = scrollLeft - walk
    })
  }
}
</script>

<style scoped>
.scroll-container {
  overflow: hidden;
  white-space: nowrap;
  cursor: grab;
  user-select: none; /* Prevent text selection */
}

.scroll-container.active {
  cursor: grabbing;
}

.scroll-content {
  display: inline-block;
}
</style>
